{% extends main.html %}

{% block content %}
<div id="chatbox">
    <div class="messages_window">
    </div>
    <div class="control_panel"><input type="text" id="message" /></div>
</div>
<script>

function escape_html(str) {
    if(str) {
        return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
    } else {
        return '';
    };
}
$(document).ready(function () {
    var ws = new WebSocket('ws://' + window.location.host +'/incoming');
    ws.onmessage = function(event) {
        package = JSON.parse(event.data)
        $msg_window = $('#chatbox .messages_window');
        $msg_window.append(
            '<div><b>' + escape_html(package.user) + ':</b> ' + escape_html(package.message) + '</div>'
        );
        $msg_window.scrollTop($msg_window[0].scrollHeight);
    }
    $('#message').keypress(function(e) {
        if(e.which == 13) {
            message = $('#message').val();
            $.get('/send_message', {
                'message': message,
            });
            $('#message').val('');
        };
    });
});
</script>
{% end %}
